package com.example.ivos.dictoption.service.impl;

import com.example.ivos.base.exception.ServiceException;
import com.example.ivos.base.response.StatusCode;
import com.example.ivos.dict.mapper.DictMapper;
import com.example.ivos.dict.pojo.entity.Dict;
import com.example.ivos.dict.pojo.vo.DictVO;
import com.example.ivos.dictoption.mapper.DictOptionMapper;
import com.example.ivos.dictoption.pojo.dto.DictOptionParam;
import com.example.ivos.dictoption.pojo.dto.DictOptionQuery;
import com.example.ivos.dictoption.pojo.entity.DictOption;
import com.example.ivos.dictoption.pojo.vo.DictOptionVO;
import com.example.ivos.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DictOptionServiceImpl implements DictOptionService {

    @Autowired
    private DictOptionMapper dictOptionMapper;

    @Autowired
    private DictMapper dictMapper;

    @Override
    public List<DictOptionVO> select(DictOptionQuery dictOptionQuery) {
        log.debug("查询字典项列表dictOptionQuery:{}", dictOptionQuery);
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionQuery, dictOption);
        List<DictOptionVO> dictOptionVOList = dictOptionMapper.select(dictOption);
        return dictOptionVOList;
    }

    @Override
    public void save(DictOptionParam dictOptionParam) {
        log.debug("保存字典项业务dictOptionParam:{}", dictOptionParam);
        DictOption dictOption=new DictOption();
        BeanUtils.copyProperties(dictOptionParam,dictOption);
        if(dictOption.getId()==null){
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insert(dictOption);
        }else{
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.update(dictOption);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("删除字典项业务id:{}", id);
        dictOptionMapper.delete(id);
    }

    @Override
    public List<DictOptionVO> selectByCode(String code) {
        log.debug("根据code查询字典项信息code:{}", code);
        Dict dict=new Dict();
        dict.setCode(code);
        List<DictVO> select = dictMapper.select(dict);
        if(select.size()>0&&select!=null){
            Long dictId = select.get(0).getId();
            DictOption dictOption=new DictOption();
            dictOption.setDictId(dictId);
            List<DictOptionVO> dictOptionVOS = dictOptionMapper.select(dictOption);
            return dictOptionVOS;
        }else{
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
    }
}
